<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>
        添加项目
    </title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <link rel="stylesheet" href="../../../css/main.css" media="all">
    <link rel="stylesheet" href="../../../lib/layui/css/layui_2.5.7.css">
    <script type="text/javascript" src="../../../lib/loading/okLoading.js"></script>
    <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet">

</head>

<style>
    /* .layui-form-label {
        width: 112px !important;
    } */
    .layui-tab {
        /* text-align: left !important;
        margin: 10px 0px; */
        overflow: auto !important;
    }
    .layui-upload-file {
        height: 0 !important;
    }

    #customerIdDiv , #templateIdDiv{
        display: flex;
        justify-content: space-between;
    }

</style>

<body>
<div class="x-body">
    <form class="layui-form layui-form-pane">
        <div class="layui-tab-content">
            <span style="font-weight:bold">基本信息</span>
            <div class="layui-form-item" style="margin-top: 8px;">
                <label class="layui-form-label">项目名称<span style="color: red;">*</span></label>
                <div class="layui-input-block">
                    <input  autocomplete="off"  type="text" name="name" lay-filter="name" lay-verify="required"  placeholder="请输入项目名称" class="layui-input">
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">客户名称<span style="color: #ff0000;">*</span></label>
                <div class="layui-input-block" id="customerIdDiv">
                    <div style="width: 100%;">
                        <select name="customerId" id="customerId" lay-filter="" lay-search="" lay-verify="required">
<!--                            <option value="">选择客户</option>-->
                        </select>
                    </div>
                    <a title="添加客户" class="ml-5 layui-btn layui-btn-normal" onclick='addModel()'>
<!--                        <i class="layui-icon">&#xe654;添加客户</i>-->添加客户
                    </a>
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">业务合作<span style="color: red;">*</span></label>
                <div class="layui-input-block">
                    <select name="businessTypeId" lay-filter="businessTypeId" lay-verify="required">
                        <option value=""></option>
                        <option value="1">销售</option>
                        <option value="2">工程</option>
                    </select>
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">业务模板<span style="color: #ff0000;">*</span></label>
                <div class="layui-input-block" id="templateIdDiv">
                    <div style="width: 100%;">
                        <select name="templateId" id="templateId" lay-filter="" lay-search="" lay-verify="required">
                            <option value="">选择模板</option>
                        </select>
                    </div>
                    <a title="预览模板" class="ml-5 layui-btn layui-btn-normal" onclick="show_template('预览模板','../template_management/template_tracking_info.html')">
                        预览模板
                    </a>
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">业务负责人</label>
                <div class="layui-input-block">
                    <select id="linkmanId" name="linkmanId" lay-filter="">
                        <option value="">请选择负责人</option>
                    </select>
                </div>
            </div>
            <span style="font-weight:bold">项目联系人</span>
            <a title="新增" class="ml-5 layui-btn layui-btn-normal" onclick='addProLinkmanModal()' style="float: right">新增
            </a>
            <div class="layui-form-item" style="margin-top: 8px;">
<!--                <table class="layui-hide" id="demo"></table>-->
                    <table class="layui-table" >
                        <thead>
                            <tr>
                                <th>姓名</th>
                                <th>职务</th>
                                <th>手机</th>
                                <th>备注</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody id="ttt">
<!--                            <tr v-for="(testData,index) in testData">-->
<!--                                <td v-text="testData.linkmanName"></td>-->
<!--                                <td v-text="testData.linkmanPosition"></td>-->
<!--                                <td v-text="testData.linkmanTel"></td>-->
<!--                                <td v-text="testData.linkmanMemo"></td>-->
<!--                            </tr>-->
                        </tbody>
                    </table>
            </div>
            <span style="font-weight:bold">备注信息</span>
            <div class="layui-form-item layui-form-text" style="margin-top: 8px;">
                <div class="layui-input-block">
                    <textarea name="memo" placeholder="备注信息。" class="layui-textarea"></textarea>
                </div>
            </div>
        </div>
        <div style="text-align: center" class="layui-form-item">
            <button class="layui-btn" type="button" lay-filter="sub" lay-submit="sub">
                保存
            </button>
        </div>
    </form>


<!-- 添加客户弹窗  开始 -->
<!-- 模态框（Modal） -->
<div class="modal fade" id="add_modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title" id="myModalLabel">
                    添加客户
                </h4>
            </div>
            <div class="modal-body">
                <form class="layui-form layui-form-pane" id="addCustomerForm">
                    <div class="layui-tab-content">
                        <div class="layui-tab-item layui-show">

                            <div class="layui-form-item">
                                <label class="layui-form-label">客户名称<span style="color: red;">*</span></label>
                                <div class="layui-input-block">
                                    <input  autocomplete="off"  type="text" id="name" name="name" lay-filter="name" lay-verify="required" placeholder="客户名称" class="layui-input">
                                </div>
                            </div>
                            <div class="layui-form-item" style="margin-top: 8px;">
                                <label class="layui-form-label">证件类型</label>
                                <div class="layui-input-block">
                                    <select name="codeType" lay-filter="codeType" id="codeType">
                                        <option value="">请选择证件类型</option>
                                        <option value="1">营业执照</option>
                                        <option value="2">身份证号</option>
                                    </select>
                                </div>
                            </div>
                            <div class="layui-form-item" style="margin-top: 8px;">
                                <label class="layui-form-label">证件代码</label>
                                <div class="layui-input-block">
                                    <input  autocomplete="off"  type="text" name="code" id="code" lay-filter="code" lay-verify="" placeholder="证件代码" class="layui-input">
                                </div>
                            </div>

<!--                            <div style="text-align: center" class="layui-form-item">-->
<!--                                <button class="layui-btn" type="button" lay-filter="sub" lay-submit="sub">-->
<!--                                    确定-->
<!--                                </button>-->
<!--                            </div>-->
                        </div>


                    </div>

                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="layui-btn" data-dismiss="modal">关闭</button>
                <button type="button" class="layui-btn" onClick="addCustomer()">添加</button>
            </div>
        </div><!-- /.modal-content -->
    </div><!-- /.modal -->
</div>

<!-- 添加项目联系人弹窗  开始 -->
<!-- 模态框（Modal） -->
<div class="modal fade" id="addProLinkman" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title">
                    添加项目联系人
                </h4>
            </div>
            <div class="modal-body">
                <form class="layui-form layui-form-pane" id="addProLinkmanForm" :model="addProLinkmanForm">
                    <div class="layui-tab-content">
                        <div class="layui-tab-item layui-show">

                            <div class="layui-form-item">
                                <label class="layui-form-label">姓名<span style="color: red;">*</span></label>
                                <div class="layui-input-block">
                                    <input  autocomplete="off"  type="text" id="linkmanName" name="linkmanName" v-model="addProLinkmanForm.linkmanName" lay-filter="linkmanName" lay-verify="required" placeholder="姓名" class="layui-input">
                                </div>
                            </div>
                            <div class="layui-form-item" style="margin-top: 8px;">
                                <label class="layui-form-label">职务</label>
                                <div class="layui-input-block">
                                    <input  autocomplete="off"  type="text" id="linkmanPosition" name="linkmanPosition" v-model="addProLinkmanForm.linkmanPosition" lay-filter="linkmanPosition" placeholder="职务" class="layui-input">
                                </div>
                            </div>
                            <div class="layui-form-item" style="margin-top: 8px;">
                                <label class="layui-form-label">手机号码</label>
                                <div class="layui-input-block">
                                    <input  autocomplete="off"  type="number" id="linkmanTel" name="linkmanTel" v-model="addProLinkmanForm.linkmanTel" lay-filter="linkmanTel" placeholder="手机号码" class="layui-input">
                                </div>
                            </div>

                            <div class="layui-form-item" style="margin-top: 8px;">
                                <label class="layui-form-label">备注</label>
                                <div class="layui-input-block">
                                    <input  autocomplete="off"  type="text" id="linkmanMemo" name="linkmanMemo" v-model="addProLinkmanForm.linkmanMemo" lay-filter="linkmanMemo" placeholder="备注" class="layui-input">
                                </div>
                            </div>
                        </div>


                    </div>

                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="layui-btn" data-dismiss="modal">关闭</button>
                <button type="button" class="layui-btn" onClick="addProLinkman()">添加</button>
<!--                <button type="button" class="layui-btn" @click="addProLinkmanVue()">添加</button>-->
            </div>
        </div><!-- /.modal-content -->
    </div><!-- /.modal -->
</div>


</div>
<script type="text/html" id="barDemo">
    <a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="del">删除</a>
</script>

<script type="text/javascript" src="../../../js/jquery.min.js"></script>
<script type="text/javascript" src="../../../js/myAjax.js"></script>
<script type="text/javascript" src="../../../js/pub.js"></script>
<script src="../../../lib/layui/layui2.5.7.js" charset="utf-8"></script>
<script src="../../../js/x-layui.js" charset="utf-8"></script>
<script src="../../../js/vue.min.js" charset="utf-8"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.3.5/js/bootstrap.min.js"></script>

<script>
    layui.use(['element', 'layer', 'form', 'laydate'], function () {
        $ = layui.jquery;//jquery
        lement = layui.element();//面包导航
        layer = layui.layer;//弹出层
        laydate = layui.laydate;//日期插件
        form = layui.form;
        okLoading.close($);
    })

</script>
<script>

    layui.use(['form', 'layer'],
        function () {
            var $ = layui.jquery;
            var form = layui.form;
            var layer = layui.layer;

            getCustomer();
            //监听业务合作选择
            form.on('select(businessTypeId)', function(data) {
                getBusinessTemplate(data.value);
                getBusinessLinkman(data.value);
                setTimeout(() => {
                    form.render('select');
                }, 200);
            });

            //监听审批提交
            form.on('submit(sub)',
                function (data) {
                    var val = data.field;
                    var selectValArr = (document.getElementById("linkmanId").options[document.getElementById("linkmanId").selectedIndex].text).split("-");
                    var addVal = {};
                    addVal.userId = $userId;
                    var project = {};
                    project.operatorId = $userId;
                    project.name = val.name;
                    project.customerId = val.customerId;
                    project.businessTypeId = val.businessTypeId;
                    project.templateId = val.templateId;
                    project.memo = val.memo;
                    addVal.project = JSON.stringify(project);
                    var projectLinkman = {};
                    projectLinkman.businessTypeId= val.businessTypeId;
                    projectLinkman.linkmanId= val.linkmanId;
                    projectLinkman.linkmanName= selectValArr[1];
                    projectLinkman.linkmanTel= selectValArr[2];
                    projectLinkman.linkmanPosition= selectValArr[0];
                    addVal.projectLinkman = JSON.stringify(projectLinkman);
                    addVal.linkmanList = JSON.stringify(jsonData);

                    let request = {
                        url: 'xa/project/addProjectNew',
                        data: addVal,
                        method: "post",
                    };
                    sendRequest(request, (data) => {
                        if (data.code === 0) {
                            layer.alert("操作成功", {
                                    icon: 6
                            },
                            function () {
                                var index = parent.layer.getFrameIndex(window.name);
                                parent.layer.close(index);
                                parent.reload();
                            });
                        } else {
                            layer.alert(data.msg, {
                                icon: 5
                            })
                        }
                    });
                    // $.ajax({
                    //     url: baseHead + "xa/project/addProjectNew",
                    //     type: 'POST',
                    //     headers: {
                    //         token: $token
                    //     },
                    //     cache: false
                    //     // ,data: JSON.stringify({
                    //     //     "userId" : $userId,
                    //     //     "project":{
                    //     //         "operatorId":$userId,
                    //     //         "name":val.name,  //名称
                    //     //         "customerId":val.customerId,       // 客户id
                    //     //         "businessTypeId":val.businessTypeId,   //业务类型id【销售1、工程2】
                    //     //         "templateId":val.templateId,       //选择模板id
                    //     //         "memo":val.memo            //备注信息
                    //     //     },
                    //     //     "businessMan":{           //业务负责人信息
                    //     //         "businessTypeId":val.businessTypeId,        //业务类型（传上面选择的销售1、工程2）
                    //     //         "linkmanId":val.linkmanId,            //负责人id(接口获取)
                    //     //         "linkmanName":selectValArr[1],    //负责人name (接口获取)
                    //     //         "linkmanTel":selectValArr[2],    //负责人tel(接口获取)
                    //     //         "linkmanPosition":selectValArr[0]  //负责人职业(接口获取)
                    //     //     },
                    //     //     "linkmanList":jsonData
                    //     // })
                    //     ,data: {
                    //         "userId" : $userId,
                    //         "project" : JSON.stringify(project),
                    //         "projectLinkman" : JSON.stringify(projectLinkman),
                    //         "linkmanList" : JSON.stringify(jsonData),
                    //     }
                    //     ,processData: false,
                    //     // contentType: "application/json",
                    //     success:function(data){
                    //         if (data.code === 0) {
                    //             layer.alert("操作成功", {
                    //                     icon: 6
                    //             },
                    //             function () {
                    //                 var index = parent.layer.getFrameIndex(window.name);
                    //                 parent.layer.close(index);
                    //                 parent.reload();
                    //             });
                    //         } else {
                    //             layer.alert(data.msg, {
                    //                 icon: 5
                    //             })
                    //         }
                    //     }
                    // });

                    return false;
                });

        });
    /*添加客户弹窗*/
    function addProLinkmanModal(){
        document.getElementById("addProLinkmanForm").reset();
        $('#addProLinkman').modal('show');
        //向模态框中传值
        //$('#updateName').val(imgName);
        // $('#updateMemo').val(imgMemo);
    };
    localStorage.removeItem('useData');  //清除本地存储
    var jsonData = JSON.parse(localStorage.getItem('useData'));
    if(!jsonData){
        jsonData = [];
    }
    else{
        // 初始化
        show();
    }
    // DOM数据到表格上
    function show(){
        $("#ttt").html("");
        for(j = 0,len=jsonData.length; j < len; j++) {
            $("#ttt").append('' +
                    '<tr>' +
                        '<td>'+jsonData[j].linkmanName+'</td>' +
                        '<td>'+jsonData[j].linkmanPosition+'</td>' +
                        '<td>'+jsonData[j].linkmanTel+'</td>' +
                        '<td>'+jsonData[j].linkmanMemo+'</td>' +
                        '<td>' +
                            '<a onclick="delLocalStorage('+j+')">删除</a>' +
                        '</td>' +
                    '</tr>');
        }
    };
    //缓存中添加联系人
    function addProLinkman() {
        // 判断
        if ($("#linkmanName").val().length == 0) {
            alert("请输入姓名！");
            return false;
        }
        jsonData.push({
            linkmanName:$("#linkmanName").val(),
            linkmanPosition:$("#linkmanPosition").val(),
            linkmanTel:$("#linkmanTel").val(),
            linkmanMemo:$("#linkmanMemo").val()
        });
        $("#linkmanName").val("");
        $("#linkmanPosition").val("");
        $("#linkmanTel").val("");
        $("#linkmanMemo").val("");
        localStorage.setItem('useData',JSON.stringify(jsonData));
        $("#ttt").empty();
        closeMe();
        show();
    }

    //删除缓存的表格中的数据
    function delLocalStorage(key) {
        // localStorage.removeItem(key);
        // for(j = 0,len=jsonData.length; j < len; j++) {
        // }
        jsonData.splice(key, 1);

        show();
        // localStorage.setItem('useData', JSON.stringify(jsonData));
        // jsonData = JSON.parse(localStorage.getItem('useData'));
        // if(!jsonData){
        //     jsonData = [];
        // }
        // else{
        //     // 初始化
        //     show();
        // }

    };
    //预览业务模板的弹窗
    function show_template(title, url, w, h) {
        // x_admin_show(title, url, w, h);
        // var selectTemplateId = sessionStorage.getItem("templateId");
        var selectTemplateId = $("#templateId ").val()
        if (selectTemplateId === '') {
            layer.alert('请选择模板！', {
                icon: 5
            })
            return false
        }
        x_admin_show(title, url+'?templateId='+selectTemplateId, w, h);
    };

    /*添加客户弹窗*/
    function addModel(){
        // $("#name").val("");
        // $("#codeType").val("");
        // $("#code").val("");
        document.getElementById("addCustomerForm").reset();
        $('#add_modal').modal('show');
        //向模态框中传值
        //$('#updateName').val(imgName);
        // $('#updateMemo').val(imgMemo);
    };

    /*添加客户到数据库*/
    function addCustomer(){
        var name = $("#name").val();
        var codeType = $("#codeType").val();
        var code=$("#code").val();
        // 判断
        if (name.length == 0) {
            layer.alert("请输入客户名称！", {
                icon: 7
            })
            return false;
        }
        if (codeType == 2) {
            //身份证号码的合法性验证
            // 身份证号码为15位或者18位，15位时全为数字，18位前17位为数字，最后一位是校验位，可能为数字或字符X
            var reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
            if(reg.test(code) === false){
                layer.alert("身份证输入不合法！", {
                    icon: 7
                })
                return false;
            }
        }

        var formData = new FormData();
        formData.append('userId',$userId);
        formData.append('name',name);
        formData.append('codeType',codeType);
        formData.append('code',code);
        $.ajax({
            url: baseHead + "xa/customer/addAndUpdate",
            type: 'POST',
            cache: false,
            headers: {
                token: $token
            },
            data: formData,
            processData: false,
            contentType: false,
            success:function(data){
                if(data.code === 0){
                    closeMe();
                    $("#customerId").empty();;
                    getCustomer();

                    layer.alert("操作成功", {
                        icon: 6
                    });
                } else {
                    layer.alert(data.msg, {
                        icon: 5
                    })
                }
            }
        });
    };

    /*弹窗关闭*/
    function closeMe(){
        $('#add_modal').modal('hide');
        $('#addProLinkman').modal('hide');
    }
    /*获取客户*/
    function getCustomer(){
        $.ajax({
            type:"get",
            url:baseHead + "xa/customer/list",
            data:{
                userId :$userId
            },
            headers: {
                token: $token
            },
            success:function(res){
                if(res.code === 0){
                    $("#customerId").append("<option value=''>请选择客户</option>");
                    for(var i =0;i < res.data.length;i++){
                        $("#customerId").append("<option value=\""+res.data[i].id+"\">"+res.data[i].name+"</option>");
                    }
                    //重新渲染
                    layui.form.render("select");
                }else{
                    layer.msg(res.message);
                }
            }
        });
    }
    /*根据业务获取业务模板*/
    function getBusinessTemplate(businessTypeId){
        document.getElementById("templateId").innerHTML = "";
        $.ajax({
        	type:"get",
            url:baseHead + "xa/template/findTemplateListNoPage",
            data:{
                userId :$userId,
                parentId:0,
                businessTypeId:businessTypeId
            },
            headers: {
                token: $token
            },
            success:function(res){
               	if(res.code == 0){
                    $("#templateId").append("<option value=''>请选择关联项目</option>");
                    for(var i =0;i < res.data.length;i++){
                        $("#templateId").append("<option value=\""+res.data[i].id+"\">"+res.data[i].name+"</option>");
                    }
                    //重新渲染
                    layui.form.render("select");
                }else{
                    layer.msg(res.message);
                }
            }
        });
    };
    /*根据业务获取业务负责人*/
    function getBusinessLinkman(businessTypeId){
        // var deptName = (businessTypeId ==1 ? '销售部':'工程部');
        document.getElementById("linkmanId").innerHTML = "";
        $.ajax({
        	type:"get",
            url:baseHead + "user/findUserSelect",
            data:{
                userId :$userId,
                // dept:deptName,
            },
            headers: {
                token: $token
            },
            success:function(res){
               	if(res.code == 0){
                    $("#linkmanId").append("<option value=''>请选择业务负责人</option>");
                    
                    for(var i =0;i < res.data.length;i++){
                        var nowDept = ((res.data[i].department) == null ? '':res.data[i].department);
                        var nowPhone = ((res.data[i].phone) == null ? '':res.data[i].phone);
                        $("#linkmanId").append("<option value=\""+res.data[i].id+"\">"+nowDept+"-"+res.data[i].nickname+"-"+nowPhone+"</option>");
                    }
                    //重新渲染
                    layui.form.render("select");
                }else{
                    layer.msg(res.message);
                }
            }
        });
    };

</script>

</body>

</html>
